package com.timguan.render.dataprocessor.processor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.timguan.render.api.entity.cms.CMSDataProcessorParamInfo;
import com.timguan.render.api.entity.dataprocessor.TabWithItem;
import com.timguan.render.dataapi.api.ICmsDataManager;
import com.timguan.render.dataapi.domain.CmsDataDO;
import com.timguan.render.dataprocessor.filter.SoldoutProductFilter4Tab;
import com.timguan.render.dataprocessor.filter.TimeVaildFilter;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * 商品Tab切换
 * Created by guankaiqiang on 2015/3/21.
 */
public class TabItemListProcessor extends DataProcessor {
    private static final Logger logger = LoggerFactory.getLogger(TabItemListProcessor.class);
    @Autowired
    private ICmsDataManager cmsDataManagerImpl;
    @Autowired
    private TimeVaildFilter timeVaildFilter;
    @Autowired
    private SoldoutProductFilter4Tab soldoutProductFilter4Tab;

    protected List<Object> execute(CommonParametersWrapper wrapper, Map<String, String> params) {
        List<Object> dataList = null;
        if (params != null && params.get(PROCESSOR_PARAM_DATALISTID) != null) {
            final int listId = Integer.valueOf(params.get(PROCESSOR_PARAM_DATALISTID));
            //每个TAB的数量上限
            final int size = StringUtils.isNotBlank(params.get(MAX_COUNT_PARAM)) && StringUtils.isNumeric(params.get(MAX_COUNT_PARAM)) ?
                    Integer.parseInt(params.get(MAX_COUNT_PARAM)) :
                    0;
            List<CmsDataDO> cmsDataDOs = cmsDataManagerImpl.selectByListId(listId);
            Map<String, String> filterParams = new HashMap<String, String>();
            if (size > 0) {
                filterParams.put(MAX_COUNT_PARAM, String.valueOf(size));
            }
            filterParams.put(START_DISPLAY_TIME, String.valueOf(System.currentTimeMillis()));
            cmsDataDOs = dataFilterChain.doFilter(cmsDataDOs, filterParams);
            Map<String, TabWithItem> itemGroupByDayMap = groupByTag(wrapper, cmsDataDOs);
            if (itemGroupByDayMap != null) {
                dataList = new ArrayList<Object>(itemGroupByDayMap.values());
            }
        }
        return dataList;
    }

    /**
     * 数据聚合
     */
    private Map<String, TabWithItem> groupByTag(CommonParametersWrapper wrapper, List<CmsDataDO> cmsDataDOs) {
        Map<String, TabWithItem> itemGroupMap = null;
        if (cmsDataDOs != null && cmsDataDOs.size() > 0) {
            itemGroupMap = new LinkedHashMap<String, TabWithItem>();
            int id = Constants.SPM_START;
            for (CmsDataDO data : cmsDataDOs) {
                try {
                    String tag = null;
                    Map<String, String> dataEntry = JSON.parseObject(data.getPropertyValue(), new TypeReference<Map<String, String>>() {
                    });
                    if (dataEntry != null) {
                        {
                            //设置spm值
                            dataEntry = setSpm(wrapper, dataEntry, id);
                            //设置数据TYPE
                            dataEntry = setDataTypeAndActionType(dataEntry);
                            id++;
                        }
                        if (StringUtils.isNotBlank(dataEntry.get(TAG))) {
                            tag = dataEntry.get(TAG);
                        }
                        if (itemGroupMap.get(tag) != null) {
                            itemGroupMap.get(tag).getItemList().add(dataEntry);
                        } else {
                            TabWithItem tabWithItem = new TabWithItem();
                            List<Object> itemList = new ArrayList<Object>();
                            itemList.add(dataEntry);
                            tabWithItem.setTag(tag);
                            tabWithItem.setItemList(itemList);
                            itemGroupMap.put(tag, tabWithItem);
                        }
                    }
                } catch (Exception e) {
                    logger.error("processor failed!", e);
                }
            }
        }
        return itemGroupMap;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        //使用时需要创建数据列表
        needCreateDatalistWhenUsed = true;
        description = "tab切换";
        paramInfos = new CMSDataProcessorParamInfo[1];
        CMSDataProcessorParamInfo dataProcessorParamInfo = new CMSDataProcessorParamInfo();
        dataProcessorParamInfo.setName(MAX_COUNT_PARAM);
        dataProcessorParamInfo.setDescription("展示数量(默认全部展示)");
        paramInfos[0] = dataProcessorParamInfo;
        dataFilterChain.add(timeVaildFilter).add(soldoutProductFilter4Tab);
    }
}
